#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <mutex>
#include <cassert>
#include <fstream>

#include "../comm/log.hpp"
#include "../comm/util.hpp"

namespace ns_LoadBalance
{
    using namespace ns_log;
    using namespace ns_util;

    class Machine
    {
    public:
        Machine(std::string ip, int port, uint64_t load)
        {
            this->_ip = ip;
            this->_port = port;
            this->_load = load;
            this->_mtx = new std::mutex();
        }
        ~Machine() {}

    public:
        void increase_load()
        {
            if (_mtx)
                _mtx->lock();
            _load++;
            if (_mtx)
                _mtx->unlock();
        }
        void decrease_load()
        {
            if (_mtx)
                _mtx->lock();
            _load--;
            if (_mtx)
                _mtx->unlock();
        }
        uint64_t Load()
        {
            uint64_t ret_load = 0;
            if (_mtx)
                _mtx->lock();
            ret_load = _load;
            if (_mtx)
                _mtx->unlock();
            return ret_load;
        }

    public:
        std::string _ip;  // 编译服务的ip
        int _port;        // 编译服务的端口
        uint64_t _load;   // 编译服务的负载
        std::mutex *_mtx; // 互斥资源锁
    };

    const std::string service_machine = "./conf/service_machine.conf";
    class loadbalance
    {
    public:
        loadbalance()
        {
            assert(loadconf(service_machine));
            LOG(INFO) << "加载" << service_machine << "成功" << "\n";
        }
        ~loadbalance() {}

    private:
        /*给我们提供编译服务的所有主机*/
        std::vector<Machine> machine;
        /*所有在线的主机id*/
        std::vector<int> online;
        /*所有离线的主机id*/
        std::vector<int> offline;

        std::mutex mtx;

    public:
        bool loadconf(const std::string &machine_list)
        {
            std::ifstream in(machine_list);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载" << machine_list << "失败" << "\n";
                return false;
            }
            std::string line;
            while (std::getline(in, line))
            {
                std::vector<std::string> tokens;
                string_util::splitstring(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "" << "\n";
                    continue;
                }
                Machine m(tokens[0], atoi(tokens[1].c_str()), 0);
                // m._ip=tokens[0];
                // m._port=atoi(tokens[1].c_str());
                // m._load=0;
                // m._mtx=new std::mutex();
                online.push_back(machine.size());
                machine.push_back(m);
            }
            in.close();
            return true;
        }

        bool smartchoice(int *id, Machine **m)
        {
            /*1.使用选择好的主机*/
            /*2.我们需要可能离线该主机*/
            mtx.lock();
            /*负载均衡算法*/
            int online_num = online.size();
            if (online_num == 0)
            {
                mtx.unlock();
                LOG(FATAL) << "现在后端所有编译服务主机已全部离线，请迅速通知运维人员进行解决" << "\n";
                LOG(FATAL) << "请耐心等待10s..." << "\n";
                sleep(10);
                onlinemachine();
                LOG(FATAL) << "主机已全部上线!" << "\n";
                return false;
            }
            // 轮询判断+最小负载选择
            *id = online[0];
            *m = &machine[online[0]];
            uint64_t min_load = machine[online[0]]._load;
            for (int i = 1; i < online.size(); i++)
            {
                if (min_load > machine[online[i]]._load)
                {
                    min_load = machine[online[i]]._load;
                    *id = online[i];
                    *m = &machine[online[i]];
                }
            }
            mtx.unlock();
            return true;
        }

        // 主机全部离线后进行统一上线
        void onlinemachine()
        {
            mtx.lock();
            online.insert(online.begin(),offline.begin(),offline.end());
            offline.erase(offline.begin(),offline.end());
            mtx.unlock();
        }

        void offlinemachine(int which)
        {
            mtx.lock();
            for (auto iter = online.begin(); iter != online.end(); iter++)
            {
                if (*iter == which)
                {
                    online.erase(iter);
                    offline.push_back(which);
                    break;
                }
            }
            mtx.unlock();
        }
    };
}
